<?php
/**
 * Created by PhpStorm.
 * User: juplus-06
 * Date: 2017/9/13
 * Time: 13:45
 */

namespace app\admin\controller;
use think\Controller;


class Suffix extends Controller
{
    public function suffixlist(){
        $data = Db('suffix')->order('id desc')->paginate(10);
        $page = $data->render();
        $this->assign('page',$page);
        $this->assign('data',$data);
        return view('suffix/index');
    }


    /**
     * 修改后缀状态
     */
    public function changeatatuid(){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['id'];
            $statuid = $post['statuid'];
            if($statuid == 1){
                $statuid = 0;
                $num = Db('suffix')->where('id',$id)->update(['statuid'=>$statuid]);
                $this->suffix_edit($post['suffix']);
                if($num>0){
                    return json(['statuid'=>$statuid,'msg'=>'修改成功']);
                }else{
                    return json(['statuid'=>$statuid,'msg'=>'修改失败']);
                }
            }else{
                $statuid = 1;
                $num = Db('suffix')->where('id',$id)->update(['statuid'=>$statuid]);
                if($num>0){
                    return json(['statuid'=>$statuid,'msg'=>'修改成功']);
                }else{
                    return json(['statuid'=>$statuid,'msg'=>'修改失败']);
                }
            }
        }
    }


    /**
     * 导入页面
     */
    public function importhtml(){
        return view('suffix/importhtml');
    }

    /**
     * 导入Excel功能
     */
    public function import(){
        if (!empty($_FILES)) {
            $file = request()->file('import');
            $info = $file->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'suffix');

            if($info){
                $file_name = './public/suffix/'.$info->getFilename();
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }

            Vendor('PHPExcel.PHPExcel');
            Vendor('PHPExcel.PHPExcel.Worksheet.Drawing');
            Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
            // 读取Excel文件内容
            $PHPReader = new \PHPExcel_Reader_Excel2007();
            $PHPExcel = $PHPReader->load($file_name);
            $currentSheet = $PHPExcel->getSheet(0);  //读取excel文件中的第一个工作表
            $allColumn = $currentSheet->getHighestColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $arr = array();  //声明数组
            /**从第二行开始输出，因为excel表中第一行为列名*/
            for($currentRow = 2;$currentRow <= $allRow;$currentRow++){

                /**从第A列开始输出*/
                for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){
                    //这部分注释不要，取出的数据不便于我们处理
                    // $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();/**ord()将字符转为十进制数*/
                    //  if($val!=''){
                    // 	 $erp_orders_id[] = $val;
                    // }
                    //数据坐标
                    $address = $currentColumn . $currentRow;
                    //读取到的数据，保存到数组$data中
                    $data[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
                    /**如果输出汉字有乱码，则需将输出内容用iconv函数进行编码转换，如下将gb2312编码转为utf-8编码输出*/
                    //echo iconv('utf-8','gb2312', $val)."\t";
                }
            }
            foreach ($data as $k => $v) {
                $where = ['suffix'=>$v['A']];
                $num = Db('suffix')->where($where)->value('id');
                if(!$num){
                    $arr['suffix'] = $v['A'];
                    $arr['companyname'] = $v['B'];
                    $num = Db('suffix')->insert(['suffix'=>$arr['suffix'],'companyname'=>$arr['companyname'],'creat_time'=>date('y-m-d h:i:s')]);
                    if($num < 0){
                        return $this->error('导入数据库失败');
                    }
                }
            }

            return $this->success('导入成功');


        }


    }


    /**
     * 导出
     */
    public function export(){
        $xlsData = Db('suffix')->select();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        $objExcel = new \PHPExcel();
        //set document Property
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        $objActSheet = $objExcel->getActiveSheet();
        $key = ord("A");
        $letter =explode(',',"A,B,C");
        $arrHeader = array('后缀','公司名','状态');
        //填充表头信息
        $lenth =  count($arrHeader);
        for($i = 0;$i < $lenth;$i++) {
            $objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]");
        };
        //填充表格信息
        foreach($xlsData as $k=>$v){
            $k +=2;
            $objActSheet->setCellValue('A'.$k,$v['suffix']);
            $objActSheet->setCellValue('B'.$k, $v['companyname']);
            // // 图片生成
            // $objDrawing[$k] = new \PHPExcel_Worksheet_Drawing();
            // $objDrawing[$k]->setPath('public/static/admin/images/profile_small.jpg');
            // // 设置宽度高度
            // $objDrawing[$k]->setHeight(40);//照片高度
            // $objDrawing[$k]->setWidth(40); //照片宽度
            // /*设置图片要插入的单元格*/
            // $objDrawing[$k]->setCoordinates('C'.$k);
            // // 图片偏移距离
            // $objDrawing[$k]->setOffsetX(30);
            // $objDrawing[$k]->setOffsetY(12);
            // $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());
            // 表格内容
            $objActSheet->setCellValue('C'.$k, $v['statuid']==1?'正常':'禁用');



            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(20);
        }

        $width = array(20,20,15,10,10,30,10,15,40);
        //设置表格的宽度
        $objActSheet->getColumnDimension('A')->setWidth($width[0]);
        $objActSheet->getColumnDimension('B')->setWidth($width[0]);
        $objActSheet->getColumnDimension('C')->setWidth($width[0]);



        $outfile = "后缀表.xls";
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outfile.'"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter->save('php://output');
    }


    /**
     * 后缀编辑页面
     */
    public function edit($id){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['id'];
            $num = Db('suffix')->where('id',$id)->update(['suffix'=>$post['suffix'],'companyname'=>$post['companyname']]);
            if($num>0){
                $this->success('更新成功');
            }else{
                $this->error('更新失败');
            }
        }
       $data = Db('suffix')->where('id',$id)->find();
       $this->assign('data',$data);
       return view('edit');
    }

    /**
     * 删除
     */
    public function delete(){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['id'];
            if(!empty($id)){
                $num = Db('suffix')->where('id',$id)->delete();
                $this->suffix_edit($post['suffix']);
                if($num>0){
                    //删除成功
                    return 1;
                }else{
                    //删除失败
                    return 2;
                }
            }else{
                //id不存在
                return 3;
            }
        }else{
            //请求格式不对
            return 4;
        }
    }



    /**
     * 添加
     */
    public function add(){
        if(request()->isPost()){
            $post = input('post.');
            $num = Db('suffix')->insert(['suffix'=>$post['suffix'],'companyname'=>$post['companyname'],'creat_time'=>date('y-m-d h:i:s')]);
            if($num>0){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }
        return view('add');
    }


    /**
     * 禁用或删除的同时修改用户状态
     */
    public function suffix_edit($suffix){
        $where['email'] = ['like',"%$suffix%"];
        $suffix = Db('user')->where($where)->select();
        foreach ($suffix as $k => $v) {
             Db('user')->where('id',$v['id'])->update(['audit'=>0]);
        }
    }



}